<?php

namespace app\controller;

use app\BaseController;
use app\common\service\UserService;
use app\wxapp\service\UserSignService;
use EasyWeChat\Factory;
use think\facade\Db;

/**
 * Class TimerTask
 * @package app\controller
 */
class TimerTask extends BaseController
{
    /**
     * 学习提醒消息推送
     */
    public function studyRemind()
    {
        // 当前时间
        $time = date('H:i');
        // 用户签到服务
        $userService = new UserSignService();
        // 如果当前时间是08:00则增加条件
        $where = "(ur.status = 2 AND ur.time = '{$time}')";
        if ('08:00' === $time) {
            $where .= 'OR(ur.status = 1)';
        }
        // 查询所有自定义为当前时间的提醒
        $list = Db::table('user_remind')
            ->alias('ur')
            ->join('wechat_user u', 'u.id = ur.uid')
            ->whereRaw($where)
            ->column('u.id,nick_name,openid,vip_expire');

        // 推送消息
        $config = [
            'app_id' => env('WXMP.APPID'),
            'secret' => env('WXMP.SECRET'),
            'token' => env('WXMP.TOKEN'),
            'response_type' => 'array',
        ];
        foreach ($list as $user) {
            // 获取用户VIP信息
            $vipInfo = UserService::getVipInfo($user['id']);
            // 获取用户总签到天数
            $signTotal = $userService->signCountTotal($user['id']);
            // 微信公众号-发送模板
            $service = Factory::officialAccount($config);
            $result = $service->template_message->send([
                'touser' => $user['openid'],
                'template_id' => config('mp.template.studyRemind'),
                'data' => [
                    'first' => '',
                    'keyword1' => $user['nick_name'],
                    'keyword2' => ($vipInfo ? ((strtotime($vipInfo['expire']) - strtotime($vipInfo['start'])) / 86400) : $signTotal) . '天',
                    'keyword3' => ($vipInfo ? $signTotal : 0) . '天',
                    'remark' => '成功贵在坚持，点击本消息继续学习吧！'
                ],
                'url' => 'http://www.doctorsclass.com/'
            ]);
            dump($user, $result, str_repeat('-', 300));
        }
    }
}